package com.engine.cese.duss.sms.util;

import com.alibaba.fastjson.JSONObject;
import it.sauronsoftware.base64.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;

import java.io.IOException;
import java.util.*;

public class UPMutil {
    /**
     *@Description: 发送post请求
     *@Param: [url, param]
     *@return: java.lang.String
     *@Author: Dusongsong
     *@Date: 2020/11/17
     */
    public static String httpPostRaw(String url,String bodys,Map<String,String> headers, String encode){
        if(encode == null){
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {

            //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);

            //设置header
            httpost.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(),entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(bodys, encode);
            httpost.setEntity(stringEntity);


            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
    /**
     * 生成随机验证码
     */
    public static String generateRandomNum() {
        int[] a = new int[6];
        Random r = new Random();
        a[0] = r.nextInt( 6 );
        for (int i = 1; i < 6; i++) {
            //数组存入6个数
            a[i] = r.nextInt( 10 );
            for (int j = 0; j < i; j++) {
                if (a[j] == a[i]) {
                    i--;
                    break;
                }
            }
        }
        // 遍历
        StringBuffer str = new StringBuffer();
        for (int s : a) {
            str.append( s );
        }
        return str.toString();
    }
    /**
     * 生成http请求头Authorization串，用于鉴权
     */
    public static String generateAuthorization(String username, String password) {
        String md5Pwd = DigestUtils.md5Hex(password);
        String pair = username + ":" + md5Pwd;
        return Base64.encode(pair,"UTF-8");
    }
    public static String getMassJsonContent(String phone,String content) {
        JSONObject messageData = new JSONObject( );
        List<Object> items = new ArrayList<>( );
        JSONObject data = new JSONObject( );
        data.put("to",phone);
        items.add(data);
        messageData.put("batchName","中电二建");
        messageData.put("items",items);
        messageData.put("content",content);
        messageData.put("msgType","sms");
        messageData.put("bizType","100");
        return messageData.toJSONString();
    }
    public static boolean sendSMS(String phone,String content){
        BaseBean baseBean = new BaseBean();
        String massURL = baseBean.getPropValue( "hodo","url");
        String username =  baseBean.getPropValue( "hodo","username");
        String password =  baseBean.getPropValue( "hodo","password");
        String param = UPMutil.getMassJsonContent( phone, content );
        Map<String, String> headers = new HashMap<>();
        String authorization = UPMutil.generateAuthorization( username, password );
        headers.put( "accept", "application/json" );
        headers.put( "Content-Type", "application/json; charset=utf-8" );
        headers.put( "Authorization", authorization );
        String encode = "UTF-8";
        try {
            String result = UPMutil.httpPostRaw( massURL, param, headers, encode );
            RecordSet rs = new RecordSet();
            JSONObject resultJson = JSONObject.parseObject( result );
            String code = resultJson.getString( "code" );
            if ("0".equals( code )) {
                String status = "0";
                String curtime = DateUtil.getFullDate();
                UUID MIT_UUID = UUID.randomUUID();
                String uuid = MIT_UUID.toString(); //唯一标志uuid
                String sql = "insert into uf_smscode (uuid,smscode,mobile,status,systemdate) values (?,?,?,?,?)";
                rs.executeUpdate( sql, new Object[]{uuid, content,phone,status, curtime} );
                return  true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        }
        return true;
    }
}

